<?php

namespace app\adminapi\controller;

use app\helpers\Common;

use think\facade\Db;
use think\Request;

class Region extends Base
{
    public function initialize()
    {
        parent::initialize();

        $this->modelName = 'Region';

        $this->defaultOrder = 'id ASC';
    }

    /**
     * Tree
     */
    public function tree(Request $request)
    {
        $param = $request->param();

        $className = '\\app\\' . $this->appName . '\\model\\' . $this->modelName;
        $model = new $className;
        $list = $model->getTreeDatas();

        $data = [
            'data' => $list
        ];

        return api_response(self::STATUS_SUCCESS, '', $data);
    }

    /**
     * 处理列表数据
     */
    protected function handleListData($data)
    {
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->modelName;
        $model = new $className;

        //$data = $model->formatDatas($data);
        foreach ($data as &$item) {
            if ($this->sourceUi == self::SOURCE_UI_2) {
                if ($item['level'] < 3) {
                    $item['isLeaf'] = false;
                } else {
                    $item['isLeaf'] = true;
                }
            } else {
                if ($item['level'] < 3) {
                    $item['hasChildren'] = true;
                    $item['children'] = [];
                }
            }
        }

        return $data;
    }

    /**
     * 筛选条件
     */
    protected function getFilterWhere($request)
    {
        $param = $request->param();
        $where = [];
        if (isset($param['parent_code']) && $param['parent_code']) {
            $where[] = ['parent_code', '=', $param['parent_code']];
        } else {
            $where[] = ['level', '=', 0];
        }

        return $where;
    }

    protected function afterInsert($data)
    {
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->modelName;
        $model = new $className;
        $model->getTreeDatas(true);

        return parent::afterInsert($data);
    }

    protected function afterUpdate($data, $info = [])
    {
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->modelName;
        $model = new $className;
        $model->getTreeDatas(true);

        return parent::afterUpdate($data);
    }

    protected function afterDelete($data)
    {
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->modelName;
        $model = new $className;
        $model->getTreeDatas(true);

        return parent::afterDelete($data);
    }
}
